package service

import (
	"fmt"
	"mime/multipart"
	"os"
	"strings"
	"time"

	"im/common"
	"im/dao"
	"im/errcode"
	"im/model"
	"im/service/alioss"
)

var fileLimit = map[string]interface{}{
	"image": nil,
	"video": nil,
	"audio": nil,
}

type Attachments interface {
	// 返回path路径或error
	UploadToOss(model.Users, multipart.File, *multipart.FileHeader) (string, error)
}

func NewAttachments() Attachments {
	return attachments{d: dao.NewAttachmentsDao()}
}

type attachments struct {
	d *dao.AttachmentsDao
}

func (a attachments) UploadToOss(u model.Users, file multipart.File, fileHeader *multipart.FileHeader) (string, error) {
	var path string
	// 格式校验
	mime := fileHeader.Header.Get("Content-Type")
	mimeSplit := strings.Split(mime, "/")
	if len(mimeSplit) != 2 {
		return "", errcode.NewError(errcode.UploadFileTypeNotSupported)
	}
	if _, ok := fileLimit[mimeSplit[1]]; !ok {
		return "", errcode.NewError(errcode.UploadFileTypeNotSupported)
	}
	// 生成文件名
	hashName := common.Sha1FromReader(file)
	timeStr := time.Now().Format("20060102")
	path = fmt.Sprintf("/uploads/%s/%s/%s.%s", mimeSplit[0], timeStr, hashName, mimeSplit[1])

	// 开始上传
	ossClient, err := alioss.NewOss()
	if err != nil {
		return "", errcode.NewError(errcode.OssCreateError, err)
	}
	path, err = ossClient.UploadFile(path, file, mime+";")
	if err != nil {
		return "", errcode.NewError(errcode.OssUploadError, err)
	}

	// 存入attachments表
	dao.NewAttachmentsDao().Create(model.AttachmentsCreatable{
		AppsId: u.AppsId,
		Url:    fmt.Sprintf("https://%s/%s", os.Getenv("OSS_BUCKET_HOST"), path),
		Mime:   mime,
		Size:   fileHeader.Size,
		Sha1:   hashName,
	})
	return path, nil
}
